package thread.java20230112;

import java.util.concurrent.Semaphore;

/**
 * 信号量
 */
public class Demo52 {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(4);

        Runnable runnable = ()->{
            try {
                String name = Thread.currentThread().getName();
                //如果申请不到资源, 会一直阻塞
                semaphore.acquire();//申请资源
                System.out.println(name +"申请到资源");
                Thread.sleep(5000);
                System.out.println(name+ "释放资源");
                semaphore.release();
            }catch (Exception e){
                e.printStackTrace();
            }
        };
        for (int i = 0; i < 20; i++) {
            new Thread(runnable, "线程"+ i).start();
        }
    }


}
